﻿using Microsoft.Office.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Automation;
using System.Windows.Forms;
using Office = Microsoft.Office.Core;
using Outlook = Microsoft.Office.Interop.Outlook;

// TODO:   按照以下步骤启用功能区(XML)项:

// 1. 将以下代码块复制到 ThisAddin、ThisWorkbook 或 ThisDocument 类中。

//  protected override Microsoft.Office.Core.IRibbonExtensibility CreateRibbonExtensibilityObject()
//  {
//      return new Ribbon1();
//  }

// 2. 在此类的“功能区回调”区域中创建回调方法，以处理用户
//    操作(如单击某个按钮)。注意: 如果已经从功能区设计器中导出此功能区，
//    则将事件处理程序中的代码移动到回调方法并修改该代码以用于
//    功能区扩展性(RibbonX)编程模型。

// 3. 向功能区 XML 文件中的控制标记分配特性，以标识代码中的相应回调方法。  

// 有关详细信息，请参见 Visual Studio Tools for Office 帮助中的功能区 XML 文档。


namespace UDMOutlook
{
    [ComVisible(true)]
    public class Ribbon1 : Office.IRibbonExtensibility
    {
        private Office.IRibbonUI ribbon;
        private static bool _isCH = true;
        public Ribbon1()
        {
            
        }
        /// <summary>
        /// 只有当新建或是编辑邮件时，菜单才可见
        /// </summary>
        /// <param name="control"></param>
        /// <returns></returns>
        public bool GetVisible(IRibbonControl control)
        {
            var inspector = control.Context as Outlook.Inspector;
            return inspector?.CurrentItem is Outlook.MailItem;
        }
        /// <summary>
        /// 菜单获取图标方法
        /// </summary>
        /// <param name="control"></param>
        /// <returns></returns>
        public Image GetImage(Office.IRibbonControl control)
        {
            switch (control.Tag.ToString())
            {
                case "DcmAI"://DCM更新AI登记
                    return Properties.Resources.AI;
            }
            return null;
        }
        private string FindTextBoxValue(string targetBoxName)
        {
            string result = null;

            try
            {
                AutomationElement rootElement = AutomationElement.RootElement;

                // 遍历所有属于当前进程的顶级窗口（过滤Outlook窗口）
                var condition = new PropertyCondition(AutomationElement.ProcessIdProperty, Process.GetCurrentProcess().Id);
                AutomationElementCollection outlookWindows = rootElement.FindAll(TreeScope.Children, condition);

                foreach (AutomationElement window in outlookWindows)
                {
                    // 匹配Outlook Inspector窗口类名（常见类名）
                    if (window.Current.ClassName.Contains("rctrl_renwnd32") ||
                        window.Current.ClassName.Contains("AfxWndW"))
                    {
                        // 构建目标文本框的查找条件
                        Condition textBoxCondition = new AndCondition(
                            new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit),
                            new PropertyCondition(AutomationElement.NameProperty, targetBoxName)
                        );

                        AutomationElement targetEdit = window.FindFirst(TreeScope.Descendants, textBoxCondition);
                        if (targetEdit != null)
                        {
                            // 尝试获取文本框内容
                            if (targetEdit.TryGetCurrentPattern(ValuePattern.Pattern, out object pattern))
                            {
                                result = ((ValuePattern)pattern).Current.Value;
                            }
                            else if (targetEdit.TryGetCurrentPattern(TextPattern.Pattern, out pattern))
                            {
                                result = ((TextPattern)pattern).DocumentRange.GetText(-1);
                            }
                        }
                    }
                }
                //return "[未找到文本框]";
                return result;
            }
            catch (Exception ex)
            {
                return result;
            }
        }
        private string FindToRecipientText(AutomationElement root, string key)
        {
            // 遍历所有顶级窗口，寻找 Outlook 的 Inspector 窗口
            var condition = new PropertyCondition(AutomationElement.ProcessIdProperty, Process.GetCurrentProcess().Id);
            AutomationElementCollection outlookWindows = root.FindAll(TreeScope.Children, condition);

            foreach (AutomationElement window in outlookWindows)
            {
                // 根据窗口类名筛选（Outlook 的 Inspector 窗口类名通常是 "rctrl_renwnd32" 或 "AfxWndW"）
                if (window.Current.ClassName.Contains("rctrl_renwnd32") ||
                    window.Current.ClassName.Contains("AfxWndW"))
                {
                    // 在窗口中查找 "收件人" 输入框
                    //string toBoxName = "收件人"; // 根据语言调整：英文用 "To"
                    string toBoxName = key; // 根据语言调整：英文用 "To"
                    var toCondition = new AndCondition(
                        new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit),
                        new PropertyCondition(AutomationElement.NameProperty, toBoxName)
                    );

                    AutomationElement toEdit = window.FindFirst(TreeScope.Descendants, toCondition);
                    if (toEdit != null)
                    {
                        if (toEdit.TryGetCurrentPattern(ValuePattern.Pattern, out object pattern))
                        {
                            return ((ValuePattern)pattern).Current.Value;
                        }
                        else if (toEdit.TryGetCurrentPattern(TextPattern.Pattern, out pattern))
                        {
                            return ((TextPattern)pattern).DocumentRange.GetText(-1);
                        }
                    }
                }
            }
            return "未找到收件人输入框";
        }
        public void btnAI_Click(Office.IRibbonControl control)
        {
            try
            {
                // 发送Tab键使焦点移出
                SendKeys.SendWait("{TAB}");
                Application.DoEvents(); // 处理消息队列
                string toText = null;
                string copyText = null;
                string subject = null;

                try
                {
                    // 获取当前用户界面语言的 LCID
                    int lcid = Globals.ThisAddIn.Application.LanguageSettings.get_LanguageID(Office.MsoAppLanguageID.msoLanguageIDUI);

                    // 根据 LCID 判断语言
                    System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo(lcid);
                    System.Threading.Thread.CurrentThread.CurrentUICulture = culture;

                    // 判断语言
                    if (culture.Name.ToLower() == "zh-cn")// 中文
                    {
                        
                    }
                    else if (culture.Name.ToLower() == "en-us")// 英文
                    {
                        _isCH = false;
                    }
                    Outlook.Inspector inspector = Globals.ThisAddIn.Application.ActiveInspector();
                    if (inspector == null || !(inspector.CurrentItem is Outlook.MailItem mailItem)) return;

                    // 关键点：直接通过 AutomationElement.RootElement 遍历
                    AutomationElement rootElement = AutomationElement.RootElement;

                    if (_isCH)
                    {
                        copyText = FindTextBoxValue("抄送");
                        toText = FindTextBoxValue("收件人");
                        subject = FindTextBoxValue("主题");
                    }
                    else
                    {
                        copyText = FindTextBoxValue("CC");
                        toText = FindTextBoxValue("To");//Recipient
                        subject = FindTextBoxValue("Subject");
                    }
                    //MessageBox.Show("收件人: " + toText);
                    //MessageBox.Show("抄送: " + copyText);
                    //MessageBox.Show("主题: " + subject);
                    //Outlook.Inspector inspector = control.Context as Outlook.Inspector;
                    if (inspector?.CurrentItem is Outlook.MailItem mail)
                    {
                        // 添加抄送人
                        if (copyText == null)
                        {
                            mail.CC = "cex@uaes.com";
                        }
                        else if (!copyText.Contains("cex@uaes.com"))
                        {
                            mail.CC = copyText + ";" + "cex@uaes.com";
                        }
                        
                        // 添加主题前缀
                        if (mail.Subject == null)
                        {
                            mail.Subject = "[AI-DCM数据集成]";
                        }
                        else if (!mail.Subject.StartsWith("[AI-DCM数据集成]"))
                        {
                            mail.Subject = "[AI-DCM数据集成]" + mail.Subject;
                        }

                        mail.Save();
                        //MessageBox.Show("AI参数已自动填充");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("错误: " + ex.Message);
                }
                
            }
            catch (Exception ex)
            {
                //MessageBox.Show($"操作失败: {ex.Message}");
            }
        }
        #region IRibbonExtensibility 成员

        public string GetCustomUI(string ribbonID)
        {
            return GetResourceText("UDMOutlook.Ribbon1.xml");
        }

        #endregion

        #region 功能区回调
        //在此处创建回叫方法。有关添加回叫方法的详细信息，请访问 https://go.microsoft.com/fwlink/?LinkID=271226

        public void Ribbon_Load(Office.IRibbonUI ribbonUI)
        {
            this.ribbon = ribbonUI;
        }

        #endregion

        #region 帮助器

        private static string GetResourceText(string resourceName)
        {
            Assembly asm = Assembly.GetExecutingAssembly();
            string[] resourceNames = asm.GetManifestResourceNames();
            for (int i = 0; i < resourceNames.Length; ++i)
            {
                if (string.Compare(resourceName, resourceNames[i], StringComparison.OrdinalIgnoreCase) == 0)
                {
                    using (StreamReader resourceReader = new StreamReader(asm.GetManifestResourceStream(resourceNames[i])))
                    {
                        if (resourceReader != null)
                        {
                            return resourceReader.ReadToEnd();
                        }
                    }
                }
            }
            return null;
        }

        #endregion
    }
}
